//
//  SettlementViewController.m
//  PalmChangtu
//
//  Created by shaorui on 15/6/18.
//  Copyright (c) 2015年 PalmChangtu. All rights reserved.
//

#import "SettlementViewController.h"
#import "SettlementTabCell.h"
#import "SettlementTabCell.h"
#import "SettlementViewController.h"
#import "CommentViewController.h"
#import "commentsCell.h"
#import "BaseUrlConfig.h"
#import "BannerCell.h"
#import "ShareUserModel.h"
#import "MainTabbarController.h"
#import "JSONKit.h"
#import "Common.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "AFNetworking.h"
#import "BaseUrlConfig.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "all_commodity_TypeModel.h"
#import "localJSONModel.h"
#import "MTLJSONAdapter.h"
#import "GetRemandModle.h"
#import "ShangPinListModel.h"
#import "PurchaseCarModel.h"
#import "SVProgressHUD.h"
#import "FreightTicketViewController.h"
#import "ShippingAddressViewController.h"

@interface SettlementViewController ()

@end

@implementation SettlementViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}

-(void)viewDidAppear:(BOOL)animated
{
    [self settiementwebGetFreighActionRequest];




}
-(void)getYouHuiQuanShuLiang:(NSString *)YouHuiQuanNum
{

    if (YouHuiQuanNum.integerValue<0 )
    {
        YouHuiQuanNum =[NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:0]];
    }

    self.labYHNum.text  =[NSString stringWithFormat:@"%@",YouHuiQuanNum];

    
    self.freightTicketNo = [NSString stringWithFormat:@"%@",YouHuiQuanNum];
}
-(void)getBuyerDeliveryInfo:(getBuyerDeliveryInfoModel *)valueModel andTypeIDStr:(NSString *)typestr
{
    NSLog(@"get backcall value=%@",valueModel);
    self.labName.text  =valueModel.receiverName;
    self.labAddress.text = [NSString stringWithFormat:@"%@%@%@",valueModel.receiverDistrict,valueModel.reStreet,valueModel.receiverAddress];


    self.labTell.text = valueModel.receiverPhone;


    for (NSDictionary * dic  in _arrYunFeiData) {


        if ([typestr isEqualToString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"type_id"]]]) {


            self.strYunFeiPrice = [NSString stringWithFormat:@"%@",[dic objectForKey:@"price"]];

            float yunfei = self.strYunFeiPrice.floatValue;

            self.labYunFei.text  =[NSString stringWithFormat:@"¥%.2f",yunfei];


        }




    }



    if ([self.strYiJianGouMai isEqualToString:@"strYiJianGouMai"]) {


        ShangPinListModel * model = [_arrData objectAtIndex:0];
        self.labPrice.text = [NSString stringWithFormat:@"¥%@",model.price];
        float allPrice =  model.price.floatValue + self.strYunFeiPrice.floatValue + _freightTicketNo.floatValue;

        self.labTatal.text  =[NSString stringWithFormat:@"¥%.2f",allPrice];
    }

    else if ([self.strYiJianGouMai isEqualToString:@"SettlementViewController"])
    {



        self.labPrice.text = [NSString stringWithFormat:@"¥%@",_allTotalprice];
        float allPrice =  _allTotalprice.floatValue + self.strYunFeiPrice.floatValue + _freightTicketNo.floatValue;
        
        self.labTatal.text  =[NSString stringWithFormat:@"¥%.2f",allPrice];
        
        
        
    }
    
    


}
- (void)viewDidLoad {

    [super viewDidLoad];
    [_v_Top.lalTitel setText:@"结算"];
    [_v_Top.btnGoback setHidden:NO];
    _v_Top.parentController = self.navigationController;

    _arrYunFeiData = [[NSMutableArray alloc] init];
    UINib *nibCell = [UINib nibWithNibName:NSStringFromClass([SettlementTabCell class]) bundle:nil];
    [self.tableView registerNib:nibCell forCellReuseIdentifier:[NSString stringWithFormat:@"%@", [SettlementTabCell class]]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;


    self.labPrice.text  =[NSString stringWithFormat:@"¥%@",self.allTotalprice];
    self.labTatal.text  =[NSString stringWithFormat:@"¥%@",self.allTotalprice];


    [_v_Top.btnGoback removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];

    [_v_Top.btnGoback addTarget:self action:@selector(btnGobackAction:) forControlEvents:UIControlEventTouchUpInside];


    [_btnSure removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnSure addTarget:self action:@selector(btnSureAction:) forControlEvents:UIControlEventTouchUpInside];
    UITapGestureRecognizer * singletap = [[UITapGestureRecognizer alloc] init];
    [singletap addTarget:self action:@selector(viewAddressAction:)];

    singletap.numberOfTapsRequired = 1;

    [self.viewAddress addGestureRecognizer:singletap];
    UITapGestureRecognizer * viewFreightTicketTap = [[UITapGestureRecognizer alloc] init];
    [viewFreightTicketTap addTarget:self action:@selector(viewFreightTicketAction:)];
    
    viewFreightTicketTap.numberOfTapsRequired = 1;
    
    [self.viewFreightTicket addGestureRecognizer:viewFreightTicketTap];
    [self.tableView reloadData];





    // Do any additional setup after loading the view from its nib.
}

-(void)viewFreightTicketAction:(UITapGestureRecognizer *)freightTicketAction
{
    
    
    FreightTicketViewController * viewFreightTic = [[FreightTicketViewController alloc] initWithNibName:@"FreightTicketViewController" bundle:nil];

    viewFreightTic.delegate  = self;
    [self presentViewController:viewFreightTic animated:YES completion:0];
    
}



-(void)viewAddressAction:(UITapGestureRecognizer *)gets
{

    ShippingAddressViewController * shop = [[ShippingAddressViewController alloc] initWithNibName:@"ShippingAddressViewController" bundle:nil];

    shop.viewString  =@"ShippingAddressViewController";
    
    shop.delegate = self;
    
    [self presentViewController:shop animated:YES completion:^{

        ;
    }];


    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    
    
    
    
    for (UITouch * touch in event.allTouches) {
        
        NSLog(@"is touch.view =  %@", touch.view);
        [self logTouchAction:touch];
        
        
        
        
        
        
    }
    
    
    
}

-(void)logTouchAction:(UITouch *)userTouch
{

    
        //    查找点的的shi
    if (userTouch.view == self.view) {
        
        
        [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
        [self.view endEditing:YES];
        NSLog(@"is _viwe");
        
        
    }
    if (userTouch.view == self.viewTouch1) {
        
        
        [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
        [self.view endEditing:YES];
        NSLog(@"is _viwe");
        
        
    }
    
    if (userTouch.view == self.viewTouch3) {
        
        
        [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
        [self.view endEditing:YES];
        NSLog(@"is viewsub");
        
        
    }
    
    if (userTouch.view == self.viewTouch2) {
        
        
        [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
        [self.view endEditing:YES];
        NSLog(@"is viewLable");
        
        
    }
    
    
    
    
}

-(void)btnGobackAction:(UIButton *)action
{

    
    [self dismissViewControllerAnimated:YES completion:0];
}

#pragma mark - standard tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
        // Return the number of sections.
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    return 120;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{



        if([_arrData count])
        {
            return [_arrData count];
        }
    else

        return 0;

    
    
}


#pragma mark - Standard TableView delegates
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * identifier = @"SettlementTabCell";
    SettlementTabCell * Cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    Cell.selectionStyle  = UITableViewCellSelectionStyleNone;
    

if([_strYiJianGouMai isEqualToString:@"strYiJianGouMai"])
{
    if ([_arrData count]!=0) {
        
        
        ShangPinListModel  * dicModel  = [_arrData objectAtIndex:indexPath.row];


        Cell.labPrce.text  = [NSString
                              stringWithFormat:@"%@",dicModel.price];
        Cell.labProdectName.text = dicModel.name;
        Cell.labXx.text =@"1X";
    [Cell.imageProdect sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HostImage,dicModel.photoUrl]] placeholderImage:[UIImage imageNamed:@"SDWebImageDefault"]];
    }
}
    else if ([_strYiJianGouMai isEqualToString:@"SettlementViewController"])
    {

        if ([_arrData count]!=0) {


            PurchaseCarModel  * dicModel  = [_arrData objectAtIndex:indexPath.row];


            Cell.labPrce.text  = [NSString
                                  stringWithFormat:@"%@",dicModel.price];
            Cell.labProdectName.text = dicModel.name;
            Cell.labXx.text =[NSString stringWithFormat:@"购买的数量%@",dicModel.commodityNo];
            [Cell.imageProdect sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HostImage,dicModel.photoUrl]] placeholderImage:[UIImage imageNamed:@"SDWebImageDefault"]];

        }
    }

    return Cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
        //    InDeliveryTabCell * cell =  (InDeliveryTabCell *)[tableView cellForRowAtIndexPath:indexPath];
        //    cell.contentView.backgroundColor = [UIColor clearColor];
        //
        //
        //    ProdectDetailViewController * detail  = [[ProdectDetailViewController alloc] initWithNibName:@"ProdectDetailViewController" bundle:nil  ];
        //
        //    [self.navigationController pushViewController:detail animated:YES ];
    
    
    
}
- (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated
{
    
        //    InDeliveryTabCell * cell =  (InDeliveryTabCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        //    cell.contentView.backgroundColor = [UIColor clearColor];
    
    
    
}
-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    return YES;
}

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}


-(void)btnSureAction:(UIButton *)sureAction
{


    self.freight = _strYunFeiPrice;
    if (strIsEmpty(self.freight)) {
        self.freight = @"0";
    }
    _freightTicketNo =@"1";
    if ([self.strYiJianGouMai isEqualToString:@"strYiJianGouMai"])
    {


        ShareUserModel * shareUser  = [ShareUserModel shareUserModel];

        NSDictionary * params = @{

                                  @"freight":[NSString stringWithFormat:@"%@",self.freight],
                                  @"Addressed":[NSString stringWithFormat:@"%@",self.labAddress.text],
                                  @"content":[NSString stringWithFormat:@"%@",self.textVeiwContentr.text],
                                  @"freighstTicketNo":_freightTicketNo,
                                  @"commodityNo":[NSNumber numberWithInteger:1],
                                  @"commodityId":self.shangPingId,
       
                                  };



        [self settiementActionRequest:params andUrl:settleAccounts_immediateAction];

    }

    else if ([self.strYiJianGouMai isEqualToString:@"SettlementViewController"])

    {

        ShareUserModel * shareUser  = [ShareUserModel shareUserModel];

        NSMutableArray  * arrOrider =[[NSMutableArray alloc] init];



        for (PurchaseCarModel * model in _arrData ) {

            [arrOrider addObject:model.orderId];

        }
        NSDictionary *  params = @{

                                   @"freight":[NSString stringWithFormat:@"%@",_freight],
                                   @"addressId":[NSString stringWithFormat:@"%@",self.labAddress.text],
                                   @"content":[NSString stringWithFormat:@"%@",self.textVeiwContentr.text],
                                   @"ids":arrOrider,

                                   @"freightTicketNo":_freightTicketNo,
                                   @"commodityNo":[NSString stringWithFormat:@"1"],

                                   @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                                   @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId],
                                   @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id]
                                   
                                   };
        
        
        
        [self settiementActionRequest:params andUrl:settleAccountsAction];
        

    }

}


#pragma mark - network request settiement

-(void)settiementActionRequest:(NSDictionary * )params andUrl:(NSString *)url
{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,url];




    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self aSettelmentActionSuccessWith:dicRespon];

         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObject9WithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}

-(void)aSettelmentActionSuccessWith :(NSDictionary *)dicRespon
{



    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
    {

        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];

    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
    }
    
}

#pragma mark - network request webGetFreightAction  获取运费

-(void)settiementwebGetFreighActionRequest
{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServerGetArea,webGetFreightAction];




    [manager POST:strUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self webGetFreightActionSuccessWith:dicRespon];

         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObject9WithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}

-(void)webGetFreightActionSuccessWith :(NSDictionary *)dicRespon
{



    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
    {

        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];



        NSMutableArray * arr = [dicRespon objectForKey:@"list"];
        _arrYunFeiData = arr;

//        [self dismissViewControllerAnimated:YES completion:^{
//
//        }];

    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
